<template>
  <Form ref="formRef" :model="formParams">
    <Row>
      <Col span="4">
        <FormItem label="医疗机构" prop="areaID">
          <Select v-model="formParams.areaID" style="width: 200px" @on-change="areaChg">
            <Option v-for="item in area" :value="item.areaID" :key="item.areaID">{{
              item.name
            }}</Option>
          </Select>
        </FormItem>
      </Col>
      <Col span="4">
        <FormItem label="科室" prop="categoryID">
          <TreeSelect :data="treeList.data" v-model="formParams.categoryID" style="width: 200px">
          </TreeSelect>
        </FormItem>
      </Col>
      <Col span="8">
        <FormItem label="结算日期">
          <el-date-picker
            v-model="settlementDate"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </FormItem>
      </Col>
      <Col span="3">
        <Space style="margin-left: 20px">
          <Button type="primary" icon="md-search" @click="goSearch">查询</Button>
          <Button type="dashed" icon="md-refresh" @click="clear">重置</Button>
        </Space>
      </Col>
    </Row>
  </Form>
  <Row style="padding-top: 30px">
    <Col span="24" style="margin-bottom: 20px">
      <div class="chart-container">
        <el-card style="width: 33%">
          <div class="chart-header">
            <h3>结余趋势</h3>
          </div>
          <div style="width: 100%; height: 350px" id="line1"></div>
        </el-card>
        <el-card style="width: 33%">
          <div class="chart-header">
            <h3>费用结构</h3>
          </div>
          <div style="width: 100%; height: 350px" id="line2"></div>
        </el-card>
        <el-card style="width: 33%">
          <div class="chart-header">
            <h3>收费项目TOP10</h3>
            <el-button type="primary" link @click="showFeeDetails">查看科室收费明细</el-button>
          </div>
          <div style="width: 100%; height: 350px" id="line3"></div>
        </el-card>
      </div>
    </Col>
  </Row>
  <Row style="padding-top: 30px">
    <Col span="24" style="margin-bottom: 20px">
      <div style="display: flex; align-items: center">
        <div style="width: 4px; height: 22px; background-color: #409eff; margin-right: 5px"></div>
        <h2 style="color: #409eff">病组列表</h2>
      </div>
    </Col>
  </Row>

  <el-table :data="tableData" border style="width: 100%">
    <!-- DRG模式的列 -->
    <template v-if="policy === 'DIP'">
      <el-table-column prop="name" align="center" label="病组名称" />
      <el-table-column prop="code" align="center" label="病组编码" />
      <el-table-column prop="total" align="center" label="总费用(万元)" sortable />
      <el-table-column prop="remain" align="center" label="结余" sortable />
      <el-table-column prop="cnt" align="center" label="病例数" sortable>
        <template #default="scope">
          <el-button link>{{ scope.row.cnt }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="zqz" align="center" label="总分值" sortable />
      <el-table-column prop="cjfy" align="center" label="次均费用" sortable />
      <el-table-column prop="cjjy" align="center" label="次均结余" sortable />
      <el-table-column prop="jczb" align="center" label="检查占比" sortable />
      <el-table-column prop="jyzb" align="center" label="检验占比" sortable />
      <el-table-column prop="yzb" align="center" label="药占比" sortable />
      <el-table-column prop="hzb" align="center" label="耗占比" sortable />
      <el-table-column prop="standardAmount" align="center" label="居民标杆值" />
      <el-table-column prop="workerStandard" align="center" label="职工标杆值" />
      <el-table-column prop="max_dc" align="center" label="超支最多医生" show-overflow-tooltip>
        <template #default="scope">
          <el-button link>{{ scope.row.max_dc }}</el-button>
        </template>
      </el-table-column>
    </template>

    <!-- DIP模式的列 -->
    <template v-else-if="policy === 'DRG'">
      <el-table-column prop="name" align="center" label="病组名称" />
      <el-table-column prop="code" align="center" label="DRG编码" />
      <el-table-column prop="remain" align="center" label="结余" sortable />
      <el-table-column prop="cnt" align="center" label="病例数" sortable>
        <template #default="scope">
          <el-button link>{{ scope.row.cnt }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="cjfy" align="center" label="次均费用" sortable />
      <el-table-column prop="zgffbz" align="center" label="职工总费用标杆值" />
      <el-table-column prop="jmffbz" align="center" label="居民总费用标杆值" />
      <el-table-column prop="cjjy" align="center" label="次均结余" sortable />
      <el-table-column prop="avgBalance" align="center" label="加工费用结构数据"> </el-table-column>
    </template>

    <el-table-column fixed="right" align="center" label="操作" width="120">
      <template #default="scope">
        <el-button type="primary" link @click="handleDetail(scope.row)">查看费用明细</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-container">
    <el-pagination
      v-model:current-page="formParams.pageNo"
      v-model:page-size="formParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <fee-details ref="feeDetailsRef" />
</template>
<script setup>
import * as echarts from 'echarts'
import { onActivated, onMounted, onBeforeUnmount } from 'vue'
import { Download, CaretTop, CaretBottom } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
import { useCommonStore } from '@/stores/common.js'
const commonStore = useCommonStore()
const policy = ref('')
policy.value = commonStore.getPolicy()
const props = defineProps({
  id: {
    type: [String, Number],
    required: true,
  },
})

import moment from 'moment'
import http from '@/util/http1'
import FeeDetails from '../components/feeDetails.vue'
import { ref } from 'vue'

let formParams = ref({
  startDate: '',
  endDate: '',
  areaID: '1',
  categoryID: '',
  pageNo: 1,
  pageSize: 10,
})
const total = ref(0)

const handleSizeChange = (val) => {
  formParams.value.pageSize = val
  goSearch()
}

const handleCurrentChange = (val) => {
  formParams.value.pageNo = val
  goSearch()
}

const handleDetail = (row) => {
  feeDetailsRef.value?.open(row.id, '病组')
}

const tableData = ref([
  policy.value === 'DRG'
    ? {
        name: 'XXXX',
        code: 'AH19',
        totalAmount: 1999.01,
        balance: -423211,
        caseCount: 123,
        trend: 'up',
        totalWeight: 43423,
        avgExpense: 10222,
        avgBalance: -3212,
        checkoutRate: '90%',
      }
    : {
        name: 'XXXX',
        code: 'AH19',
        balance: -423211,
        caseCount: 123,
        avgExpense: 10222,
        workerStandard: '',
        standardAmount: '',
        avgBalance: -3212,
      },
])

const area = ref([])
const initArea = async () => {
  try {
    const response = await http.get('/Basic/Area/ListByUser', {})
    area.value = response.data
    if (area.value.length > 0) {
      formParams.value.areaID = route.query.areaID || area.value[0].areaID
    }
    return area.value
  } catch (error) {
    return []
  }
}

const areaChg = (areaID) => {
  formParams.value.areaID = areaID
  initTreeList()
}

let treeList = reactive({ data: [] })
const initTreeList = () => {
  return http
    .get('/Basic/Category/TreeList?areaID=' + formParams.value.areaID, {})
    .then((response) => {
      treeList.data = formatTreeData(response.data)
      return treeList.data
    })
    .catch((error) => {
      return []
    })
}

const formatTreeData = (data) => {
  return data.map((item) => ({
    title: item.title,
    value: item.categoryID,
    expand: true,
    children: item.children ? formatTreeData(item.children) : null,
  }))
}

let lineChart1 = null
let lineChart2 = null
let lineChart3 = null

const lineList1 = ref({
  xAxis: ['2021-01', '2021-02', '2021-03', '2021-04', '2021-05', '2021-06'],
  legend: ['总收入', '支付差'],
  series: [
    {
      name: '总收入',
      type: 'line',
      data: [389, 672, 534, 967, 766, 422],
      itemStyle: {
        color: '#5470c6',
      },
    },
    {
      name: '支付差',
      type: 'line',
      data: [46, 272, 166, 565, 481, 41],
      itemStyle: {
        color: '#91cc75',
      },
    },
  ],
})

const lineList2 = ref({
  series: [
    {
      type: 'pie',
      radius: '70%',
      label: {
        formatter: '{b}: {c}%',
      },
      data: [
        { value: 30, name: '材料' },
        { value: 25, name: 'XX' },
        { value: 30, name: '其他' },
        { value: 10, name: '检查' },
        { value: 5, name: '检验' },
      ],
    },
  ],
})

const lineList3 = ref({
  series: [
    {
      type: 'bar',
      barWidth: '60%',
      data: [
        { value: 50000, name: 'XXY药品' },
        { value: 35000, name: 'XXXX材料' },
        { value: 25000, name: 'XXX检查' },
        { value: 15000, name: 'XXXSs' },
        { value: 8000, name: 'XXXXXX' },
      ],
      label: {
        show: true,
        position: 'right',
        formatter: '{c}元',
      },
      barWidth: 30,
      barMaxWidth: 30,
      itemStyle: {
        color: '#5470c6',
      },
    },
  ],
  yAxis: ['XXY药品', 'XXXX材料', 'XXX检查', 'XXXSs', 'XXXXXX'],
})

const initCharts = () => {
  initLine1()
  initLine2()
  initLine3()
}

const initLine1 = () => {
  const line1 = document.getElementById('line1')
  lineChart1 = echarts.init(line1)
  updateLine1Chart()
}

const initLine2 = () => {
  const line2 = document.getElementById('line2')
  lineChart2 = echarts.init(line2)
  updateLine2Chart()
}

const initLine3 = () => {
  const line3 = document.getElementById('line3')
  lineChart3 = echarts.init(line3)
  updateLine3Chart()
}

const updateLine1Chart = () => {
  if (!lineChart1) return

  const option1 = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: lineList1.value.legend,
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: lineList1.value.xAxis,
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
      name: '金额（万元）',
      nameTextStyle: {
        padding: [0, 0, 0, 40],
      },
    },
    series: lineList1.value.series,
  }
  lineChart1.setOption(option1)
}

const updateLine2Chart = () => {
  if (!lineChart2) return

  const option2 = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%',
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      itemWidth: 10,
      itemHeight: 10,
    },
    series: lineList2.value.series,
  }
  lineChart2.setOption(option2)
}

const updateLine3Chart = () => {
  if (!lineChart3) return

  const option3 = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '25%',
      right: '15%',
    },
    xAxis: {
      type: 'value',
      name: '金额（元）',
    },
    yAxis: {
      type: 'category',
      data: lineList3.value.yAxis,
    },
    series: lineList3.value.series,
  }
  lineChart3.setOption(option3)
}

const initData = async () => {
  try {
    formParams.value.startDate =
      route.query.startDate || moment().subtract(1, 'year').format('YYYY-MM-DD HH:mm:ss')
    formParams.value.endDate = route.query.endDate || moment().format('YYYY-MM-DD HH:mm:ss')
    settlementDate.value = [
      moment(formParams.value.startDate).toDate(),
      moment(formParams.value.endDate).toDate(),
    ]
    await initArea()
    await initTreeList()
    if (route.query.categoryID) {
      formParams.value.categoryID = route.query.categoryID
    } else if (route.query.name && treeList.data.length > 0) {
      const categoryID = findCategoryIDByName(treeList.data, route.query.name)
      formParams.value.categoryID = categoryID || ''
    }

    await goSearch()
  } catch (error) {}
}

onMounted(async () => {
  initCharts()
  await initData()
})

onActivated(async () => {
  await initData()
})

const formRef = ref(null)
const feeDetailsRef = ref(null)

const settlementDate = ref([])
const clear = () => {
  settlementDate.value = [moment().subtract(1, 'year').toDate(), moment().toDate()]
  formParams.value.pageNo = 1
  formRef.value.resetFields()
}

const goSearch = async () => {
  if (settlementDate.value && settlementDate.value.length) {
    formParams.value.startDate = moment(settlementDate.value[0]).format('YYYY-MM-DD HH:mm:ss')
    formParams.value.endDate = moment(settlementDate.value[1]).format('YYYY-MM-DD HH:mm:ss')
  } else {
    formParams.value.startDate = formParams.value.endDate = ''
  }

  const params = Object.assign({}, formParams.value, {
    id: props.id,
  })

  const baseParams = {
    startDate: params.startDate,
    endDate: params.endDate,
    areaID: params.areaID,
    categoryID: params.categoryID,
  }

  const listParams = {
    ...baseParams,
    type: params.type,
    pageNo: params.pageNo,
    pageSize: params.pageSize,
  }

  try {
    const [res1, res2] = await Promise.all([
      http.post('/Statistic/Category/DetailPageList', toRaw(listParams)),
      http.post('/Statistic/Category/DetailPart1', toRaw(baseParams)),
    ])

    tableData.value = res1.data.list || []
    total.value = res1.data.total || 0

    lineList1.value.legend = res2.data.line.legend || []
    lineList1.value.xAxis = res2.data.line.xAxis || []
    lineList1.value.series[0].data = res2.data.line.series[0].datas || []
    lineList1.value.series[1].data = res2.data.line.series[1].datas || []

    lineList2.value.series[0].data = res2.data.pie || []

    lineList3.value.yAxis = res2.data.chargeInfoItems.map((item) => item.itemName) || []
    lineList3.value.series[0].data = res2.data.chargeInfoItems.map((item) => item.amount) || []

    updateLine1Chart()
    updateLine2Chart()
    updateLine3Chart()
  } catch (error) {
    console.error('数据获取失败:', error)
  }
}
const showFeeDetails = () => {
  feeDetailsRef.value?.open(props.id, '科室')
}

const findCategoryIDByName = (treeData, name) => {
  for (let node of treeData) {
    if (node.title === name) {
      return node.value
    }
    if (node.children) {
      const found = findCategoryIDByName(node.children, name)
      if (found) return found
    }
  }
  return null
}

window.addEventListener('resize', () => {
  lineChart1?.resize()
  lineChart2?.resize()
  lineChart3?.resize()
})

onBeforeUnmount(() => {
  lineChart1?.dispose()
  lineChart2?.dispose()
  lineChart3?.dispose()
})
</script>

<style lang="less" scoped>
:deep(.el-button--link:focus) {
  outline: none;
  border: none;
  box-shadow: none;
}
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }
}
.chart-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px;
}
.chart-container {
  display: flex;
  justify-content: space-between;
}
.el-date-range-picker {
  width: 680px !important;
}
.el-date-range-picker .el-picker-panel__body {
  min-width: 640px;
}

.custom-year-cell {
  padding: 4px;
  text-align: center;
}

.cell-buttons {
  display: flex;
  gap: 4px;
  justify-content: center;
  margin-top: 4px;
}

.cell-buttons .el-button {
  flex: 1;
  min-width: 60px;
}

.el-picker-panel {
  min-width: 200px !important;
}

.half-year-cell {
  padding: 8px 0;
  text-align: center;
}

.year-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.half-year-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
}

.half-year-buttons .el-button {
  flex: 1;
  margin: 0;
  padding: 4px 0;
}

.half-year-buttons .divider {
  width: 1px;
  height: 16px;
  background-color: #dcdfe6;
  margin: 0 4px;
}

.half-year-buttons .active {
  color: var(--el-color-primary);
  font-weight: bold;
}

.el-picker-panel.el-date-picker {
  min-width: 280px !important;
}

.el-year-table td {
  padding: 8px 0;
}
</style>
````
